<?php

namespace App\Http\Controllers\Admin\RoomManager;

use App\Exceptions\BasicException;
use App\Http\Controllers\BaseController;
use Illuminate\Http\Request;

//引用http请求类
use App\Response\Response;
use Illuminate\Support\Facades\DB;

class BackgroundImageController extends BaseController
{

    /**
     * @api {post} /room/background-image 背景图-创建
     * @apiVersion 0.1.0
     * @apiName 房间管理-背景图-创建
     * @apiGroup 房间管理
     *
     * @apiParam {string} name 名称 必传
     * @apiParam {string} picture 图片 必传
     * @apiParam {string} effect_picture 效果圖 必传
     * @apiParam {string} is_free 是否免费，1：是；0：否，必传
     * @apiParam {int} sell_status 出售状态 1上架 2下架 必传
     * @apiParam {string} day_price 指定天数费用
     *
     * @apiSuccessExample 成功响应
     *
     *      {"code":200,"data":true}
     *
     * @apiError 10001 参数校验失败
     *
     * @apiErrorExample 错误响应
     *
     *      {
     *          "code": 10001,
     *          "message": "errorMsg"
     *      }
     *
     */
    public function create(Request $request)
    {
        //参数校验
        $v = app('validator')->make($request->all(),
            [
                'name'           => 'required|string',
                'picture'        => 'required|string|active_url',
//                'effect_picture' => 'required|string|active_url',
                'day_price'      => 'filled',
//                'sell_status'    => 'required|in:1,2',
            ]);
        if ($v->fails()) throw new BasicException(10001, getValidateMessage($v->messages()));

        $params = $request->only(['name', 'picture', 'effect_picture', 'sell_status', 'is_free']);
        $day_price = $request->input('day_price','');

        $res = app('repo_room');
        $params['add_time'] = time();

        DB::beginTransaction();
        try {
            $rows = $res->addBackgroundImage($params);
            if (!$rows) {
                throw new BasicException(10001, "插入失败！");
            }

            if ($rows && $day_price){
                $day_price_arr  = [];
                if (!is_array($day_price)){
                    $day_price = json_decode($day_price,true);
                }
                foreach ($day_price as $key=>$value){
                    if (!isset($value['day']) || !$value['day'] || !isset($value['price']) || !$value['price']) {
                        continue;
                    }
                    $value['room_background_id']= $rows->id;
                    $day_price_arr[]= $value;
                }
                if ($day_price_arr){
                    $res->addBackgroundPrice($day_price_arr);
                }
            }
            DB::commit();
            return Response::sendData(true);
        } catch (\Exception $e) {
            DB::rollBack();
            throw new BasicException(0, $e->getMessage());
        }
    }

    /**
     * @api {delete} /room/background-image 背景图-删除
     * @apiVersion 0.1.0
     * @apiName 房间管理-背景图-删除
     * @apiGroup 房间管理
     *
     * @apiParam {string} ids                       字符串分割的id 必传
     *
     * @apiSuccessExample 成功响应
     *
     *      {"code":200,"data":true}
     *
     * @apiError 10001 参数校验失败
     *
     * @apiErrorExample 错误响应
     *
     *      {
     *          "code": 10001,
     *          "message": "errorMsg"
     *      }
     *
     */
    public function del(Request $request)
    {
        //参数校验
        try {
            $this->validate($request, [
                'ids' => 'required|string',
            ]);

        } catch (\Exception $e) {
            throw new BasicException(10001, json_encode($e->errors()));
        }

        $idsStr = $request->input("ids");
        $idsArr = explode(",", $idsStr);

        DB::beginTransaction();
        try {
            $rows = app('repo_room')->delBackgroundImage($idsArr);
            if (!$rows) {
                throw new BasicException(10001, "删除失败！");
            }

            foreach ($idsArr as $idValue) {
                app('repo_room')->delBackgroundPrice($idValue);
            }

            DB::commit();
            return Response::sendData(true);
        } catch (\Exception $e) {
            DB::rollBack();
            throw new BasicException(0, $e->getMessage());
        }
    }

    /**
     * @api {put} /room/background-image 背景图-修改
     * @apiVersion 0.1.0
     * @apiName 房间管理-背景图-修改
     * @apiGroup 房间管理
     *
     *
     * @apiParam {int} id
     * @apiParam {string} name 名称 必传
     * @apiParam {string} picture 图片 必传
     * @apiParam {string} effect_picture 效果圖 必传
     * @apiParam {string} is_free 是否免费 0否 1是
     * @apiParam {int} sell_status 出售状态 1上架 2下架 必传
     *
     * @apiSuccessExample 成功响应
     *
     *      {"code":200,"data":true}
     *
     * @apiError 10001 参数校验失败
     *
     * @apiErrorExample 错误响应
     *
     *      {
     *          "code": 10001,
     *          "message": "errorMsg"
     *      }
     *
     */
    public function update(Request $request)
    {
        //参数校验
        $v = app('validator')->make($request->all(),
            [
                'id'           => 'required|integer',
                'name'           => 'required|string',
                'picture'        => 'required|string|active_url',
//                'effect_picture' => 'required|string|active_url',
//                'sell_status'    => 'required|in:1,2',
                'day_price'      => 'filled',
            ]);
        if ($v->fails()) throw new BasicException(10001, getValidateMessage($v->messages()));

        $params = $request->only(['id', 'name', 'picture', 'effect_picture', 'sell_status', 'is_free']);
        $params['effect_picture'] = $params['picture'];
        $id = $params['id'];
        $day_price = $request->input(['day_price']);

        DB::connection("mysql")->transaction(function () use($params, $day_price, $id) {
            $rows = app('repo_room')->saveBackgroundImage(["id" => $id], $params);

            if (!$rows) {
                throw new BasicException(10001, "更新失败！");
            }
            if (!is_array($day_price)){
                $day_price = json_decode($day_price,true);
            }

            if ($day_price){
                app('repo_room')->delBackgroundPrice($id);
                foreach ($day_price as  $key=>$value){
                    if (!isset($value['day']) || !$value['day'] || !isset($value['price']) || !$value['price']) {
                        continue;
                    }
                    $value['room_background_id'] = $id;
                    app('repo_room')->addBackgroundPrice($value);
                }
            }
        }, 5);

        return Response::sendData(true);
    }

    /**
     * @api {get} /room/background-image 背景图-列表
     * @apiVersion 0.1.0
     * @apiName 房间管理-背景图-列表
     * @apiGroup 房间管理
     *
     * @apiParam {number} page 当前页数 可选
     * @apiParam {number} perPage 分页容量 可选
     * @apiParam {string} add_time 添加时间 可选
     * @apiParam {string} name 名称 可选
     * @apiParam {number} price 价格 可选
     * @apiParam {number} day 天数 可选
     *
     *
     * @apiSuccessExample 成功响应
     *
     *
     * {
     * "code": 200,
     * "data": {
     * "list": [
     * {
     * "id(序号)": 31,
     * "picture(图片)": "http://yutangyuyin1.oss-cn-hangzhou.aliyuncs.com/room/backgroud/6215ae17cd175cad6526304ae6886586Fop4g.jpeg",
     * "name(图片名称)": "哈哈1233",
     * "effect_picture(效果图片)": "http://yutangyuyin.oss-cn-hangzhou.aliyuncs.com/admin_images/5ead32b47e557.png",
     * "sell_status(出售状态 1上架 2下架 必传)": 1,
     * "is_free(是否免费 0否 1是)": 1,
     * "update_time(更新时间)": "2021-07-08 18:02:54",
     * "room_background_products_price": [
     * {
     * "id": 5,
     * "room_background_id": 56,
     * "price(价格)": 1000,
     * "day(天数)": 7
     * },
     * {
     * "id": 6,
     * "room_background_id": 56,
     * "price": 2000,
     * "day": 15
     * },
     * {
     * "id": 7,
     * "room_background_id": 56,
     * "price": 3000,
     * "day": 30
     * }
     * ]
     * }
     * ],
     * "meta": {
     * "page": 1,
     * "limit": 10,
     * "next": null,
     * "total": 1
     * }
     * }
     * }
     *
     *
     */
    public function list(Request $request)
    {
        //参数校验
        try {
            $this->validate($request, [
                'perPage' => 'filled|numeric',
                'page'    => 'filled|numeric',
            ]);
        } catch (\Exception $e) {
            throw new BasicException(10001, json_encode($e->errors()));
        }
        $param = $request->all();
        $where_price = $where_product =[];

        if (isset($param['add_time'])){
            $search_time = [strtotime($param['add_time']),strtotime($param['add_time'])+86400];
            $where_product[] =[function($query) use ($search_time){
                $query->whereBetween('add_time',$search_time);
            }];
        }
        if (isset($param['name'])){
            $title  = $param['name'];
            $where_product[] =[function($query) use($title){
                $query->where('name','like',"%{$title}%");
            }];
        }

        if (isset($param['is_free'])){
            if ($param['is_free']==1){
                $where_price[] =['price',0];
            }elseif($param['is_free'] == 0) {
                $where_price[] = ['price','>', 0];
            }
        }
        if (isset($param['price'])){
            $where_price[]=['price',$param['price']];
        }
        if (isset($param['day'])){
            $where_price[]=['day',$param['day']];
        }

        $list = app('repo_room')->getBackgroundImageQueryList($request->input(),$where_price,$where_product);
        foreach ($list as $key => $val) {
            $val['add_time'] = date('Y-m-d H:i:s', $val->add_time);
        }

        return Response::sendList($list);
    }

    /**
     * @api {post} /room/background-image/give 背景图-赠送
     * @apiVersion 0.1.0
     * @apiName 背景图-赠送
     * @apiGroup 房间管理
     *
     * @apiParam {number} id     产品主键，必传
     * @apiParam {number} user_code   用户编号，必传
     * @apiParam {number} use_days     使用天数，必传
     *
     * @apiSuccessExample 成功响应
     * {"code":200,"data":true}
     */

    public  function background_give(Request $request){
        //参数校验
        $v = app('validator')->make($request->all(),
            [
                'id' => 'required',
                'user_code' => 'required|numeric',
                'use_days' => 'required|numeric|min:1',
            ]);
        if ($v->fails()) throw new BasicException(10001, getValidateMessage($v->messages()));
        $param = $request->only(['id','user_code','use_days']);
        $where_user[] =['user_code',$param['user_code']];
        $user_id = app('repo_user_data')->getUserId($where_user);

        $where[] =['id',$param['id']];
        $detail = app('repo_room')->getBackgroundImageInfo($where);

        if ($detail){
            app("repo_room")->give($param['id'], $user_id, $param['use_days']);
        }else{
            throw new BasicException(30005);
        }

        return Response::sendData(true);
    }

    /**
     * @api {get} /room/background-image/buy_log 背景图-购买记录列表
     * @apiVersion 0.1.0
     * @apiName 房间管理-背景图-购买记录列表
     * @apiGroup 房间管理
     *
     * @apiParam {number} page 当前页数 可选
     * @apiParam {number} perPage 分页容量 可选
     * @apiParam {string} add_time 添加时间 可选
     * @apiParam {string} name 名称 可选
     * @apiParam {number} price 价格 可选
     * @apiParam {number} day 天数 可选
     * @apiParam {number} buy_user_id 购买者用户id 可选
     * @apiParam {string} buy_user_name 购买者用户名称 可选
     *
     *
     * @apiSuccessExample 成功响应
     *
     *
     * {
     * "code": 200,
     * "data": {
     * "list": [
     * {
     * "id 主键": 3,
     * "room_background_id 背景主键id": 56,
     * "room_background_name 背景图名称": "3.4.0测试",
     * "buy_user_id 购买者用户id": 88,
     * "buy_user_name 购买者用户名称": "88管理员",
     * "use_user_id 使用者用户id": 547177,
     * "use_user_name 使用者用户昵称": "111佳人有约",
     * "price 价格": 1000,
     * "day 金额": 7,
     * "picture 展示图": "http://yutangyuyin.oss-cn-hangzhou.aliyuncs.com/admin_images/5ead32b47e557.png",
     * "effect_picture 效果图": "http://yutangyuyin.oss-cn-hangzhou.aliyuncs.com/admin_images/5ead32b47e557.png",
     * "renew_number 续费次数": 1,
     * "add_time 添加时间": "2021-07-12 09:49:45",
     * "overdue_time 过期时间": 1626659385
     * }
     * ],
     * "meta": {
     * "page": 1,
     * "limit": "10",
     * "next": null,
     * "total": 1
     * }
     * }
     * }
     *
     *
     */
    public function buy_log_list(Request $request)
    {
        //参数校验
        try {
            $this->validate($request, [
                'perPage' => 'filled|numeric',
                'page'    => 'filled|numeric',
            ]);
        } catch (\Exception $e) {
            throw new BasicException(10001, json_encode($e->errors()));
        }
        $param = $request->all();
        $where_price = $where_product =[];

        if (isset($param['add_time'])){
            $search_time = [strtotime($param['add_time']),strtotime($param['add_time'])+86400];
            $where_product[] =[function($query) use ($search_time){
                $query->whereBetween('add_time',$search_time);
            }];
        }
        // 主题名称
        if (isset($param['name'])){
            $title  = $param['name'];
            $where_product[] =[function($query) use($title){
                $query->where('room_background_name','like',"%{$title}%");
            }];
        }
        // 购买者名称
        if (isset($param['buy_user_name'])){
            $buy_user_name  = $param['buy_user_name'];
            $where_product[] =[function($query) use($buy_user_name){
                $query->where('buy_user_name','like',"%{$buy_user_name}%");
            }];
        }
        if (isset($param['buy_user_id'])){
            $buy_user_id  = $param['buy_user_id'];
            $where_product[] =[function($query) use($buy_user_id){
                $query->where('buy_user_id',$buy_user_id);
            }];
        }

        if (isset($param['price'])){
            $where_price[]=['price',$param['price']];
        }
        if (isset($param['day'])){
            $where_price[]=['day',$param['day']];
        }

        $list = app('repo_room')->getBackgroundImageBugLogList($request->input(),$where_price,$where_product);
        foreach ($list as $key => $val) {
            $val['add_time'] = date('Y-m-d H:i:s', $val->add_time);
        }

        return Response::sendList($list);
    }
}
